package kr.hkit.androidcomplete02.ch12;

import java.util.ArrayList;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.content.ClipData.Item;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Ch12_ListAddDelMulti extends Activity {
	ArrayList<String> arrItems;
	ArrayAdapter<String> Adapter;
	ListView listView;
	EditText ed;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch12_listadddel);
		
		ed = (EditText) findViewById(R.id.newitem);
		
		//데이터 원본
		arrItems = new ArrayList<String>();
		arrItems.add("First");
		arrItems.add("Second");
		arrItems.add("Third");
		arrItems.add("Fourth");
		arrItems.add("fifth");
		
		//어댑터 준비
		Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, arrItems);
		
		//listview 어댑터 연결
		listView = (ListView) findViewById(R.id.list);
		listView.setAdapter(Adapter);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String text = "Select Item = " + Adapter.getItem(position);
				Toast.makeText(getApplication(), text, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	public void mOnClick(View v) {
		
		switch (v.getId()) {
		case R.id.add:
			String text = ed.getText().toString();
			if(text.length() != 0) {
				arrItems.add(text);
				ed.setText("");
				Adapter.notifyDataSetChanged();
			}
			break;
		case R.id.delete:
			SparseBooleanArray sb = listView.getCheckedItemPositions();
			if (sb.size() != 0) {
				for(int i = listView.getCount() -1; i>=0 ; i--) {
					if(sb.get(i)){
						arrItems.remove(i);
					}
				}
				listView.clearChoices();
				Adapter.notifyDataSetChanged();
			}
			break;
		}
	}
}
